package com.jinke.uang.ui.activity.validation;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.jinke.uang.R;
import com.jinke.uang.adapter.FormAdapter;
import com.jinke.uang.base.BaseNormalActivity;
import com.jinke.uang.base.BaseResponse;
import com.jinke.uang.bean.AuthUserInfoData;
import com.jinke.uang.bean.CompareData;
import com.jinke.uang.bean.IdentityData;
import com.jinke.uang.common.RouterMap;
import com.jinke.uang.camera.CameraActivity;
import com.jinke.uang.camera.PicturePreviewActivity;
import com.jinke.uang.common.GlideImageLoader;
import com.jinke.uang.common.NoDoubleClickListener;
import com.jinke.uang.common.RealNameAuthData;
import com.jinke.uang.common.UserAuthRouter;
import com.jinke.uang.common.UserInfo;
import com.jinke.uang.constant.Constant;
import com.jinke.uang.constant.HttpConstant;
import com.jinke.uang.model.AuthModule;
import com.jinke.uang.presenter.CommonPresenter;
import com.jinke.uang.permission.IPermisson;
import com.jinke.uang.permission.Permission;
import com.jinke.uang.utils.FileUtils;
import com.jinke.uang.utils.RegularExpression;
import com.jinke.uang.utils.ToastUtils;
import com.jinke.uang.utils.systemutil.UploadImageUtil;
import com.jinke.uang.utils.toolutil.ImageUtils;
import com.jinke.uang.view.ShootingDialog;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindArray;
import butterknife.BindView;
import butterknife.ButterKnife;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * 实名认证的界面,,身份信息界面
 */
@Route(path = RouterMap.REAL_NAME_AUTH_PAGE)
public class RealNameAuthActivity extends BaseNormalActivity<CommonPresenter,AuthModule> implements IPermisson {

    @BindView(R.id.topBack)
    ImageView topBack;
    @BindView(R.id.topText)
    TextView topText;
    @BindView(R.id.relIdcard)
    RelativeLayout relIdcard;
    @BindView(R.id.relIdcardHand)
    RelativeLayout relIdcardHand;
    @BindView(R.id.tvNext)
    TextView tvNext;
    @BindView(R.id.iv_positive)
    ImageView iv_positive;
    @BindView(R.id.iv_nagative)
    ImageView iv_nagative;
    @BindView(R.id.camera_page)
    FrameLayout cameraPage;
    @BindView(R.id.compared_page)
    FrameLayout comparedPage;
    @BindView(R.id.btn_confirm)
    TextView btnConfirm;
    @BindView(R.id.btn_cancel)
    TextView btnCancel;
    //绑定string里面array数组
    @BindArray(R.array.identity)
    String[] identity;

    @Autowired(name = Constant.IS_BACK)
    boolean is_back;

    // 身份证信息
    private IdentityData.IdentityBean identityBean;
    private IdentityData.ImageInfoBean imageInfoBeanPositive;
    private IdentityData.ImageInfoBean imageInfoBeanNagative;
    private List<IdentityData.ImageInfoBean> imageInfoParams;

    private RecyclerView recycler;
    private FormAdapter adapter;

    public static String REASONCODE = "orderBackReasonCode";
    private final String IDENTITY_CODE="identity_code";
    private String reasonCode;

    private Permission permission;

    //人脸识别结果 1:通过 2:未通过
    private int pass;

    @Override
    protected void initViews() {
        ButterKnife.bind(this);
        reasonCode = getIntent().getStringExtra(REASONCODE);
        if (!TextUtils.isEmpty(reasonCode)) {
            tvNext.setText(R.string.save_change);
        }
        //获取头部信息
        topText.setText(getStringResource(R.string.auth_idcard_title));

        topBack.setOnClickListener(viewclick);
        relIdcard.setOnClickListener(viewclick);
        relIdcardHand.setOnClickListener(viewclick);
        tvNext.setOnClickListener(viewclick);

    }

    /**
     * 点击信息
     */
    private NoDoubleClickListener viewclick = new NoDoubleClickListener() {
        @Override
        public void onNoDoubleClick(View v) {
            super.onNoDoubleClick(v);
            switch (v.getId()) {
                case R.id.topBack:
                    finish();
                    break;
                case R.id.relIdcard:
                    //身份证
                    showTips();
                    break;
                case R.id.relIdcardHand:
                    //手持身份证
                    permission.authPermisson(Constant.PIC_TYPE_ID_CARD_NAGATIVE);
                    break;
                case R.id.tvNext:
                    //下一步
                    submit();
                    break;

                default:
                    break;
            }
        }
    };

    @Override
    protected void onUIReady() {
        ARouter.getInstance().inject(this);
        permission = new Permission(this, this);
        //是否需要回显
        if (UserInfo.isShowUserInformation()) {
            mPresenter.getData(HttpConstant.AUTH_INFO_DATA,null,IDENTITY_CODE);
        }
        if (is_back) {
            tvNext.setText(R.string.save_change);
        }
    }

    @Override
    protected int getResId() {
        return 0;
    }

    @Override
    protected int getContentResId() {
        return R.layout.activity_auth_idcard;
    }

    @Override
    public String getPageTitle() {
        return "";
    }


    @Override
    protected CommonPresenter getPresenter() {
        return new CommonPresenter();
    }

    @Override
    protected AuthModule getModule() {
        return new AuthModule();
    }

    /**
     * 提交  先对比对比完之后保存
     */

    private void submit() {
        if (iv_positive.getDrawable() == null) {
            ToastUtils.showShort(this, R.string.auth_id_card_positive_hint);
            return;
        }
        if (iv_nagative.getDrawable() == null) {
            ToastUtils.showShort(this, R.string.auth_id_card_positive_half_body_hint);
            return;
        }
        if (null == identityBean) {
            ToastUtils.showShort(this, R.string.auth_id_card_positive_hint);
            return;
        }
        if (null == imageInfoBeanNagative) {
            ToastUtils.showShort(this, R.string.auth_id_card_positive_half_body_hint);
            return;
        }
        showLoadingView();
        mPresenter.getData(HttpConstant.IMG_COMPARE,null,imageInfoBeanPositive.getImagePath(),
                imageInfoBeanNagative.getImagePath());
    }

    private void fillImgView(AuthUserInfoData.IdentityBean identityBean) {
        List<AuthUserInfoData.IdentityBean.IdentityImagesBean> imgList = identityBean
                .getIdentityImages();
        if (imgList == null || imgList.size() == 0) return;
        for (AuthUserInfoData.IdentityBean.IdentityImagesBean image : imgList) {
            if (Constant.PIC_TYPE_ID_CARD_POSITIVE == image.getFileType()) {
                GlideImageLoader.loadIdCardImg(this, image.getImageUrl(), iv_positive);
            } else if (Constant.PIC_TYPE_ID_CARD_NAGATIVE == image.getFileType()) {
                GlideImageLoader.loadIdCardImg(this, image.getImageUrl(), iv_nagative);
            }
        }
        this.identityBean = new IdentityData.IdentityBean(identityBean);
    }

    /**
     * 展示图片
     */
    private void showDialog() {
        cameraPage.setVisibility(View.GONE);
        comparedPage.setVisibility(View.VISIBLE);
        //人脸识别页面初始化信息
        recycler = findViewById(R.id.recycler);
        recycler.setLayoutManager(new LinearLayoutManager(this));
        DividerItemDecoration divider = new DividerItemDecoration(this, DividerItemDecoration
                .VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(this, R.drawable.custom_divider));
        recycler.addItemDecoration(divider);
        adapter = new FormAdapter(this, identity, identityBean.toArray());
        recycler.setAdapter(adapter);

        btnConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String str = checkForm();
                //身份证十六位正则表达式
                String check = RegularExpression.checkRegularExpression(identityBean
                        .getIdentityCardNum(), RegularExpression.idnum, getStringResource(R
                        .string.id_num_error));
                if (!TextUtils.isEmpty(check)) {
                    ToastUtils.showShort(RealNameAuthActivity.this, check);
                    return;
                }
                if (!TextUtils.isEmpty(str)) {
                    Toast.makeText(RealNameAuthActivity.this, str, Toast.LENGTH_SHORT).show();
                    return;
                }
                if (imageInfoBeanPositive != null && imageInfoBeanNagative != null) {
                    imageInfoParams = new ArrayList<>();
                    imageInfoParams.add(imageInfoBeanPositive);
                    imageInfoParams.add(imageInfoBeanNagative);
                    mPresenter.getData(HttpConstant.SAVE_IDENTITY,null,identityBean,RealNameAuthData.getInstance().getAllData
                            (),IDENTITY_CODE, imageInfoParams, pass);
                    showLoadingView();
                }
            }
        });

        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cameraPage.setVisibility(View.VISIBLE);
                comparedPage.setVisibility(View.GONE);
            }
        });


        RealNameAuthData.getInstance().putAllData(identityBean);
    }


    private String checkForm() {
        identityBean = RealNameAuthData.getInstance().getAllData();
        if (TextUtils.isEmpty(identityBean.getRealName())) {
            return getStringResource(R.string.auth_type_real_name_hint);
        } else if (TextUtils.isEmpty(identityBean.getIdentityCardNum())) {
            return getStringResource(R.string.auth_type_real_id_card_num_hint);
        } else if (TextUtils.isEmpty(identityBean.getBirthday())) {
            return getStringResource(R.string.auth_type_birthday_hint);
        }
        return null;
    }

    /**
     * 压缩并上传
     *
     * @param filePath
     * @param compressType
     */
    public void compressImgAndDisPlayForFileString(String filePath, final int compressType) {
        Luban.with(this).ignoreBy(500).load(filePath).setTargetDir(FileUtils.getCachePicDir1())
                .setCompressListener(new OnCompressListener() {
            @Override
            public void onStart() {
                showLoadingView();
            }

            @Override
            public void onSuccess(File file) {
                if (compressType == Constant.PIC_TYPE_ID_CARD_POSITIVE) {
                    mPresenter.getData(HttpConstant.UPLOAD_IDENTITY_CARD_ONE,null,file);
                } else if (compressType == Constant.PIC_TYPE_ID_CARD_NAGATIVE) {
                    mPresenter.getData(HttpConstant.UPLOAD_SINGLE_IMG,null,2, file);
                }
            }

            @Override
            public void onError(Throwable e) {
                dismissLoadingView();
            }
        }).launch();
    }

    public void compressImgAndDisPlay(File sourceImgUri, final int compressType) {

        Luban.with(this).load(sourceImgUri).setTargetDir(FileUtils.getCachePicDir1())
                .setCompressListener(new OnCompressListener() {
            @Override
            public void onStart() {
                showLoadingView();
            }

            @Override
            public void onSuccess(File file) {
                if (compressType == Constant.PIC_TYPE_ID_CARD_POSITIVE) {
                    mPresenter.getData(HttpConstant.UPLOAD_IDENTITY_CARD_ONE,null,file);
                } else if (compressType == Constant.PIC_TYPE_ID_CARD_NAGATIVE) {
                    mPresenter.getData(HttpConstant.UPLOAD_SINGLE_IMG,null,2, file);
                }
            }

            @Override
            public void onError(Throwable e) {
                dismissLoadingView();
            }
        }).launch();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 0x1234) {
            //在这判断获取的图片文件大小是否为0 分别处理
            final String filePath = data.getStringExtra("filename");
            File file = new File(data.getStringExtra("filename"));
            if (0 == file.length()) {
                Bitmap bitmap = ImageUtils.bytes2Bitmap(PicturePreviewActivity.getImage());
                if (null == bitmap || bitmap.getAllocationByteCount() == 0) {
                    bitmap = BitmapFactory.decodeFile(data.getStringExtra("filename"));
                }
                if (null != bitmap && bitmap.getAllocationByteCount() > 0) {
                    bitmap = UploadImageUtil.getUploadNeedBitmapBYSize(bitmap);
                    if (UploadImageUtil.checkBitmapSize(bitmap)) {

                        switch (requestCode) {
                            case Constant.PIC_TYPE_ID_CARD_POSITIVE:
                                iv_positive.setImageBitmap(bitmap);
                                mPresenter.getData(HttpConstant.UPLOAD_IDENTITY_CARD,null,requestCode, bitmap);
                                break;
                            case Constant.PIC_TYPE_ID_CARD_NAGATIVE:
                                iv_nagative.setImageBitmap(bitmap);
                                mPresenter.getData(HttpConstant.UPLOAD_IDENTITY_CARD,null,requestCode, bitmap);
                                break;
                            default:
                                break;
                        }

                    } else {
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                compressImgAndDisPlayForFileString(filePath, Constant
                                        .PIC_TYPE_ID_CARD_POSITIVE);
                            }
                        }, 2500);
                    }
                } else {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            compressImgAndDisPlayForFileString(filePath, Constant
                                    .PIC_TYPE_ID_CARD_POSITIVE);
                        }
                    }, 1500);
                }
            } else {
//                Uri uri = FileUtils.fileToUri(file);
                switch (requestCode) {
                    case Constant.PIC_TYPE_ID_CARD_POSITIVE:
//                        iv_positive.setImageURI(uri);
                        compressImgAndDisPlay(file, Constant.PIC_TYPE_ID_CARD_POSITIVE);
                        break;
                    case Constant.PIC_TYPE_ID_CARD_NAGATIVE:
//                        iv_nagative.setImageURI(uri);
                        compressImgAndDisPlay(file, 2);
                        break;
                    default:
                        break;
                }

            }
        }
    }

    private void showTips() {
        final ShootingDialog shootingDialog = new ShootingDialog(this, getStringResource(R.string
                .auth_id_card_shopting_title));
        shootingDialog.show();
        shootingDialog.setOnClickListener(new ShootingDialog.CallBack() {
            @Override
            public void onConfirm() {
                permission.authPermisson(Constant.PIC_TYPE_ID_CARD_POSITIVE);
                shootingDialog.hide();
            }
        });
    }

    /**
     * 权限获取的相关
     *
     * @param result
     */
    @Override
    public void onSuccess(int result) {
        //获取完身份进行拍照的
        if (Constant.PIC_TYPE_ID_CARD_POSITIVE == result) {
            Intent intent = new Intent(this, CameraActivity.class);
            intent.putExtra(CameraActivity.TYPE, CameraActivity.TYPE_ID_CARD);
            startActivityForResult(intent, result);
        } else if (Constant.PIC_TYPE_ID_CARD_NAGATIVE == result) {
            Intent intent = new Intent(this, CameraActivity.class);
            intent.putExtra(CameraActivity.TYPE, CameraActivity.TYPE_PERSON);
            startActivityForResult(intent, result);
        }
    }

    @Override
    public void onSuccess(Object object) {}

    @Override
    public void showResponse(int apiType, String listType, Object o) {
        dismissLoadingView();
        if(apiType== HttpConstant.SAVE_IDENTITY){ //保存修改后的身份信息回調
            BaseResponse<String> response = (BaseResponse<String>) o;
            if (response.getStatus() == Constant.HTTP_OK) {
                // 跳转
                UserAuthRouter.getInstance().jumpNextPager(this, RouterMap.REAL_NAME_AUTH_PAGE);
            } else {
                ToastUtils.showShort(this, response.getMessage());
            }
        }

        else if(apiType==HttpConstant.AUTH_INFO_DATA){ //获取认证信息
            BaseResponse<AuthUserInfoData> response = (BaseResponse<AuthUserInfoData>) o;
            if (response.getStatus() == Constant.HTTP_OK) {
                fillImgView(response.getData().getIdentity());
            } else {
                ToastUtils.showShort(RealNameAuthActivity.this, response.getMessage());
            }
        }

        else if(apiType==HttpConstant.IMG_COMPARE){  //人脸对比接口
            BaseResponse<CompareData> response = (BaseResponse<CompareData>) o;
            pass = response.getData().getPass();
            if (response.getData().isCompareStatus()) {
                if (!is_back) {
                    showDialog();
                } else {
                    imageInfoParams = new ArrayList<>();
                    imageInfoParams.add(imageInfoBeanPositive);
                    imageInfoParams.add(imageInfoBeanNagative);
                    mPresenter.getData(HttpConstant.SAVE_IDENTITY,null,identityBean,IDENTITY_CODE, imageInfoParams, pass);
                }
            } else {
                ToastUtils.showShort(this, response.getMessage());
            }
        }

        else if(apiType==HttpConstant.UPLOAD_IDENTITY_CARD){
            //上传身份证信息图片
            BaseResponse<IdentityData> identityResponse = (BaseResponse<IdentityData>) o;
            if (identityResponse.getStatus() == Constant.HTTP_OK) {
                    imageInfoBeanNagative = identityResponse.getData().getImageInfo();
                    GlideImageLoader.LoadImage(RealNameAuthActivity.this, imageInfoBeanNagative
                            .getImageUrl(), iv_nagative);

            } else {
                ToastUtils.showShort(this, identityResponse.getMessage());
            }
        }
        else if(apiType==HttpConstant.UPLOAD_SINGLE_IMG){
            //上传身份证信息图片
            BaseResponse<IdentityData> identityResponse = (BaseResponse<IdentityData>) o;
            if (identityResponse.getStatus() == Constant.HTTP_OK) {
                    imageInfoBeanNagative = identityResponse.getData().getImageInfo();
                    GlideImageLoader.LoadImage(RealNameAuthActivity.this, imageInfoBeanNagative
                            .getImageUrl(), iv_nagative);

            } else {
                ToastUtils.showShort(this, identityResponse.getMessage());
            }
        }

        else if(apiType==HttpConstant.UPLOAD_IDENTITY_CARD_ONE){ //上传身份证信息图片
            BaseResponse<IdentityData> identityResponse = (BaseResponse<IdentityData>) o;
            if (identityResponse.getStatus() == Constant.HTTP_OK) {
                identityBean = identityResponse.getData().getIdentity();
                imageInfoBeanPositive = identityResponse.getData().getImageInfo();
                GlideImageLoader.LoadImage(RealNameAuthActivity.this, imageInfoBeanPositive
                        .getImageUrl(), iv_positive);

            } else {
                ToastUtils.showShort(this, identityResponse.getMessage());
            }
        }
    }

    @Override
    public void showError(Throwable e) {
        dismissLoadingView();
    }
}
